#include "Graphics.h"
#include "Color.h"

#include <SDL_image.h>
#include <stdexcept>

Graphics::Graphics(SDL_Window* window)
{
	renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
}

Graphics::~Graphics()
{
	SDL_DestroyRenderer(renderer);
}

SDL_Texture* Graphics::newTexture(std::string fileName)
{
	SDL_Texture* tex = IMG_LoadTexture(renderer, fileName.c_str());
	if (!tex)
	{
		throw std::runtime_error("Failed to load :" + fileName + " " + IMG_GetError());
	}
}

void Graphics::clear(Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
	SDL_SetRenderDrawColor(renderer, r, g, b, a);
	SDL_RenderClear(renderer);
}

void Graphics::present()
{
	SDL_RenderPresent(renderer);
}

void Graphics::drawLine(int x1, int y1, int x2, int y2)
{
	SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
	SDL_RenderDrawLine(renderer, x1, y1, x2, y2);
}

void Graphics::drawBox(int x, int y, int w, int h, int color)
{
	SDL_Rect src{ x, y, w, h };
	Color col(color);
	SDL_SetRenderDrawColor(renderer, col.r, col.g, col.b, col.a);
	SDL_RenderDrawRect(renderer, &src);
}

void Graphics::drawRect(int x, int y, int w, int h, int color)
{
	SDL_Rect src{ x, y, w, h };
	Color col(color);
	SDL_SetRenderDrawColor(renderer, col.r, col.g, col.b, col.a);
	SDL_RenderFillRect(renderer, &src);
}

void Graphics::drawTexture(SDL_Texture* tex, int x, int y)
{
	int width, height;
	SDL_QueryTexture(tex, nullptr, nullptr, &width, &height);
	SDL_Rect dst = { x, y, width, height };
	SDL_Rect src = { 0, 0, width, height };
	SDL_RenderCopy(renderer, tex, &src, &dst);
}

void Graphics::drawTexture(SDL_Texture* tex, int x, int y, int width, int height)
{
	int w, h;
	SDL_QueryTexture(tex, nullptr, nullptr, &w, &h);
	SDL_Rect dst = { x, y, width, height };
	SDL_Rect src = { 0, 0, w, h };
	SDL_RenderCopy(renderer, tex, &src, &dst);
}
